package org.example.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yc.damai.entity.DmUser;
import org.example.web.fegin.CacheDo;
import org.example.web.fegin.OtherDo;
import org.example.web.fegin.UserDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/6/20
 * Email haijunzhou@hnit.edu.cn
 */
@RestController
public class IndexDo {

    @RequestMapping("index")
    public String index(HttpServletRequest request){
        return "index " + request.getServerPort();
    }

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("user")
    @HystrixCommand(fallbackMethod="userByHystrix")
    public String user(){
        return restTemplate.getForObject("http://damai-user/user", String.class);
    }

    public String userByHystrix(){
        return "user 降级方法";
    }

    @RequestMapping("other")
    public String other(){
        return restTemplate.getForObject("http://damai-other/other", String.class);
    }

    @RequestMapping("dmUser")
    public DmUser dmUser(){
        DmUser dmUser = new DmUser();
        dmUser.setCname("张三");
        return dmUser;
    }

    @Autowired
    OtherDo otherDo;
    @Autowired
    UserDo userDo;

    @GetMapping("userByFegin")
    public String userByFegin(){
        return userDo.user();
    }

    @GetMapping("otherByFegin")
    public String otherByFegin(){
        return otherDo.other();
    }

    ////////////////////////////////////////////////////
    @RequestMapping("add/{x}/{y}")
    int add(@PathVariable int x,@PathVariable int y){
        return userDo.addNum(x,y);
    }

    @GetMapping("hello")
    String hello(String name){
        return userDo.hello(name);
    }

    @GetMapping("setPwd")
    DmUser setPwd(DmUser dmUser, String pwd){
        return userDo.setPwd(dmUser, pwd);
    }




    ///////////////////////// 业务方法////////////////////////////

    // Could not autowire. There is more than one bean of 'CacheDo' type.
    //@Autowired
    @Resource
    CacheDo cacheDo;

    @Resource
    CacheDoImpl cacheDoImpl;

    @RequestMapping("queryByIndex")
    Map<String,Object> queryByIndex(){
        Map<String, Object> stringObjectMap = cacheDo.queryByIndex();
        // 保存到降级对象中
        cacheDoImpl.setQueryByIndexCache(stringObjectMap);
        return stringObjectMap;
    }


}
